package edu.tjpu.share.newui;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.androidpn.client.Constants;
import org.androidpn.client.ServiceManager;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import edu.tjpu.share.R;
import edu.tjpu.share.app.Fields;
import edu.tjpu.share.po.FileForDownload;
import edu.tjpu.share.po.Server;
import edu.tjpu.share.po.UserVo;
import edu.tjpu.share.service.DownloadService;
import edu.tjpu.share.task.UpdateTask;
import edu.tjpu.share.util.FileUtil;
import edu.tjpu.share.util.NetworkUtil;

public class UserManage extends Activity {
	// 步骤1：声明视图组件对象
	private ListView lstViews;
	// 步骤2：声明一个全局型的List集合，用于存放List列表中的数据
	private List<Map<String, ?>> data;
	private ProgressDialog progressDialog;
	public final static int NOUPDATES = 10;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// 取消界面的标题栏
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.show_view_list_layout);
		// 初始化ListView组件
		this.lstViews = (ListView) findViewById(R.id.lstViews);
		String userData = null;
		if (accessToInternet()) {
			userData = "修改密码~您可以在这里修改您的密码#修改头像~完善您的头像资料#消息设置~接收分享消息推送设置#注销~退出登录并删除个人信息#检查更新~检查是否有新版可用#关于~Copyright-Crystal@TJPU    ";
		} else {
			userData = "消息设置~接收分享消息推送设置#注销~退出登录并删除您的个人信息#关于~Copyright-Crystal@TJPU   ";
		}
		// 步骤3：调用一个私有的方法用于初始化data数据
		UserManage.this.data = getData(userData);
		// 步骤6：调用自定义个的私有方法初始化listView组件
		UserManage.this.initListView(UserManage.this.lstViews);
		// 步骤12：将上下文菜单绑定到ListView组件中
		UserManage.this.registerForContextMenu(UserManage.this.lstViews);
		// 步骤14：将自定义监听器绑定到视图组件中
		UserManage.this.lstViews.setOnItemClickListener(new SimpleAdapterOCL());

	}

	// 步骤7：对ListView组件的封装
	private void initListView(ListView lstView) {
		// 步骤7-1：创建一个适配器对象
		SimpleAdapter adapter = new SimpleAdapter(this, this.data,
				R.layout.user_manage_layout, new String[] { "name", "details",
						"picture" }, new int[] { R.id.big_name,
						R.id.small_details, R.id.left_picture });
		// 步骤7-2：(核心)深度定制adapter适配，使其可以绑定复杂的视图组件
		adapter.setViewBinder(new SimpleAdapter.ViewBinder() {
			public boolean setViewValue(View view, Object data,
					String textRepresentation) {
				// 判断item中的Image组件
				if (view instanceof ImageView && data instanceof Bitmap) {
					ImageView imageView = (ImageView) view;
					imageView.setImageBitmap((Bitmap) data);
					return true;
				}
				return false;
			}
		});
		// 步骤7-3：将设定好的适配器绑定到ListView组件中
		lstView.setAdapter(adapter);

	}

	// 步骤4：创建一个私有的getData方法用于初始化List列表中的数据
	private List<Map<String, ?>> getData(String userData) {
		// 步骤4-1：创建一个空的List集合，用于存放item选项
		List<Map<String, ?>> lstData = new ArrayList<Map<String, ?>>();
		// 步骤4-2：获取待封装数据
		String result = fetchData(userData);
		// 步骤4-3：使用嵌套循环完成对每条信息的封装
		String[] rows = result.split("#");
		//System.out.println(rows.length);
		if (rows.length > 0) {
			for (int i = 0; i < rows.length; i++) {
				// 步骤4-4：使用Split方法继续分割数据
				String[] cols = rows[i].split("~");
				if (!cols[0].contains("anyType{")) {
					// 步骤4-5：创建一个Item选项
					Map<String, Object> item = new HashMap<String, Object>();
					// 步骤4-6：为该选项（item01）赋初值
					item.put("name", cols[0]);
					item.put("details", cols[1]);
					item.put("picture", android.R.drawable.btn_star_big_off);
					// 步骤4-7：将创建好的选项item01放入到lstData集合中
					lstData.add(item);
				}
			}
		}
		// 步骤4-8：将封装好的lstData集合返回
		return lstData;
	}

	// 编写一个内部私有的方法获取List组件中的数据（数据库，互联网）
	private String fetchData(String userData) {

		return userData.substring(0, userData.length() - 1);
	}

	// 步骤13：创建界面的监听器
	class SimpleAdapterOCL implements AdapterView.OnItemClickListener {
		public void onItemClick(AdapterView<?> adapter, View v, int position,
				long id) {
			java.io.File cache = UserManage.this.getCacheDir();
			java.io.File cacheServerinfoFile = new java.io.File(cache,
					Fields.SERVER_INFO);
			java.io.File cacheUserFile = new java.io.File(cache, Fields.USER);
			UserVo user = (UserVo) FileUtil.ReadObjectFromFile(cacheUserFile
					.getAbsolutePath());
			Server serverinfo = (Server) FileUtil
					.ReadObjectFromFile(cacheServerinfoFile.getAbsolutePath());

			Intent intent = new Intent();
			Bundle bundle = new Bundle();
			if (accessToInternet()) {
				switch (position) {
				case 0:
					// 修改密码

					bundle.putBoolean("isModify", true);
					bundle.putSerializable(Fields.SERVER_INFO, serverinfo);
					bundle.putSerializable(Fields.USER, user);
					intent.putExtras(bundle);
					intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					intent.setClass(UserManage.this, UserRegister.class);
					startActivity(intent);
					break;
				case 1:
					// 修改头像
					bundle.putSerializable(Fields.SERVER_INFO, serverinfo);
					bundle.putSerializable(Fields.USER, user);
					intent.putExtras(bundle);
					intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					intent.setClass(UserManage.this, SelectAvatar.class);
					startActivity(intent);

					break;
				case 2:
					// 推送消息设置
					ServiceManager.viewNotificationSettings(UserManage.this);
					break;
				case 3:
					// 删除密码

					new AlertDialog.Builder(UserManage.this)
							.setTitle("警告")
							.setMessage("您确定要注销吗？")
							.setNegativeButton("取消",
									new DialogInterface.OnClickListener() {

										public void onClick(
												DialogInterface dialog,
												int which) {
										}
									})
							.setPositiveButton("确定",
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog,
												int whichButton) {
											SharedPreferences sharedPrefs = getSharedPreferences(
													Constants.SHARED_PREFERENCE_NAME,
													Context.MODE_PRIVATE);
											Editor editorxmpp = sharedPrefs
													.edit();
											editorxmpp
													.remove(Constants.XMPP_USERNAME);
											editorxmpp
													.remove(Constants.XMPP_PASSWORD);
											editorxmpp.commit();
											// xmpp
											// 删除用户登录信息
											SharedPreferences share = getSharedPreferences(
													"perference", MODE_PRIVATE);
											Editor editor = share.edit();// 取得编辑器
											editor.putString(Fields.USER_NAME,
													"");
											editor.putString(
													Fields.USER_PASSWD, "");
											editor.putString(
													Fields.USER_AVATAR, "");
											editor.putBoolean("isLogedIn", false);
											editor.commit();// 提交刷新数据
											Toast.makeText(UserManage.this,
													"用户登录信息已删除！",
													Toast.LENGTH_SHORT).show();
											//ServiceManager manager = new ServiceManager(UserManage.this);
											//manager.stopService();
											Intent intent1 = new Intent();
											Bundle bundle1 = new Bundle();
											String hoststr = share.getString(
													Fields.HOST, "");
											int portnum = share.getInt(
													Fields.PORT, 8080);
											Server serverinfo = new Server();
											serverinfo.setHost(hoststr);
											serverinfo.setProt(portnum);
											bundle1.putSerializable(
													Fields.SERVER_INFO,
													serverinfo);
											intent1.putExtras(bundle1);
											intent1.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
											intent1.setClass(UserManage.this,
													Login.class);
											startActivity(intent1);
											finish();
										}
									}).show();

					break;
				case 4:
					// 检查更新
					int localVersion=0;
					try {
						localVersion = getPackageManager().getPackageInfo(getPackageName(),0).versionCode;
					} catch (NameNotFoundException e) {
						Log.w("UserManage", "Can't get localVersion");
					}
					if(localVersion!=0){
						progressDialog = ProgressDialog.show(UserManage.this, "请稍等...",
								"正在检查更新...", true);
						HashMap<String, Object> map = new HashMap<String, Object>();
						map.put("localVersion", localVersion);
						map.put(Fields.SERVER_INFO, serverinfo);
						map.put("updateHandler", updateHandler);
						new UpdateTask().execute(map);
					}
					break;
				case 5:
					// 关于
					break;
				default:
					break;
				}
			} else {
				switch (position) {
				case 0:
					// 推送消息设置
					ServiceManager.viewNotificationSettings(UserManage.this);
					break;
				case 1:
					// 删除密码

					new AlertDialog.Builder(UserManage.this)
							.setTitle("警告")
							.setMessage("您确定要注销吗？")
							.setNegativeButton("取消",
									new DialogInterface.OnClickListener() {

										public void onClick(
												DialogInterface dialog,
												int which) {
										}
									})
							.setPositiveButton("确定",
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog,
												int whichButton) {
											SharedPreferences sharedPrefs = getSharedPreferences(
													Constants.SHARED_PREFERENCE_NAME,
													Context.MODE_PRIVATE);
											Editor editorxmpp = sharedPrefs
													.edit();
											editorxmpp
													.remove(Constants.XMPP_USERNAME);
											editorxmpp
													.remove(Constants.XMPP_PASSWORD);
											editorxmpp.commit();
											// xmpp
											// 删除用户登录信息
											SharedPreferences share = getSharedPreferences(
													"perference", MODE_PRIVATE);
											Editor editor = share.edit();// 取得编辑器
											editor.putString(Fields.USER_NAME,
													"");
											editor.putString(
													Fields.USER_PASSWD, "");
											editor.putString(
													Fields.USER_AVATAR, "");
											editor.commit();// 提交刷新数据
											Toast.makeText(UserManage.this,
													"用户登录信息已删除！",
													Toast.LENGTH_SHORT).show();
											Intent intent1 = new Intent();
											Bundle bundle1 = new Bundle();
											String hoststr = share.getString(
													Fields.HOST, "");
											int portnum = share.getInt(
													Fields.PORT, 8080);
											Server serverinfo = new Server();
											serverinfo.setHost(hoststr);
											serverinfo.setProt(portnum);
											bundle1.putSerializable(
													Fields.SERVER_INFO,
													serverinfo);
											intent1.putExtras(bundle1);
											intent1.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
											intent1.setClass(UserManage.this,
													Login.class);
											startActivity(intent1);
											finish();
										}
									}).show();

					break;
				case 2:
					// 关于
					break;
				default:
					break;
				}
			}

		}
	}

	Handler updateHandler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case DownloadService.DOWNLOAD_FAILED:
				progressDialog.dismiss();
				Toast.makeText(UserManage.this,
						"服务器连接失败！",
						Toast.LENGTH_SHORT).show();
				break;
			case DownloadService.DOWNLOAD_COMPLETE:
				progressDialog.dismiss();
				Bundle bundle = msg.getData();
				final FileForDownload updateFile = (FileForDownload) bundle.getSerializable("update");
				if(updateFile!=null&&updateFile.getFurl()!=null&&!"".equals(updateFile.getFurl())){
					if (NetworkUtil.CheckMobileNetworkState(UserManage.this)) {
						new AlertDialog.Builder(UserManage.this)
						.setTitle("警告")
						.setMessage("有新版本，是否使用运营商网络下载？（可能会产生高额流量费用）")
						.setNegativeButton("等待连接至WLAN后自动下载",
								new DialogInterface.OnClickListener() {

									public void onClick(DialogInterface dialog,
											int which) {
										SharedPreferences sp = getSharedPreferences(
												"perference", MODE_PRIVATE);
										if (sp.getBoolean(
												Fields.NEED_DOWNLOAD, false)) {
											java.io.File cache = UserManage.this
													.getCacheDir();
											java.io.File cacheForDownFile = new java.io.File(
													cache,
													Fields.FOR_DOWNLOAD);
											List<FileForDownload> downWaitingList = (List<FileForDownload>) FileUtil
													.ReadObjectFromFile(cacheForDownFile
															.getAbsolutePath());
											downWaitingList.add(updateFile);
											FileUtil.writeObjectToFile(
													downWaitingList,
													cacheForDownFile
															.getAbsolutePath());
										} else {
											Editor editor = sp.edit();
											editor.putBoolean(
													Fields.NEED_DOWNLOAD,
													true);
											java.io.File cache = UserManage.this
													.getCacheDir();
											java.io.File cacheForDownFile = new java.io.File(
													cache,
													Fields.FOR_DOWNLOAD);
											List<FileForDownload> downWaitingList = new ArrayList<FileForDownload>();
											downWaitingList.add(updateFile);
											FileUtil.writeObjectToFile(
													downWaitingList,
													cacheForDownFile
															.getAbsolutePath());
											editor.commit();
										}
										Toast.makeText(UserManage.this,
												"已添加至下载列表，连接至WLAN时自动开始下载！",
												Toast.LENGTH_SHORT).show();
									}
								})
						.setPositiveButton("现在下载",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int whichButton) {
										
										java.io.File cache = UserManage.this.getCacheDir();
					             		java.io.File cacheServerinfoFile = new java.io.File(cache,
					             				Fields.SERVER_INFO);
					                	 Server serverinfo = (Server) FileUtil
					             				.ReadObjectFromFile(cacheServerinfoFile.getAbsolutePath());
										 HashMap<String, Object> mapaa = new HashMap<String, Object>();
						     				mapaa.put(Fields.FILE_NAME, UserManage.this.getResources().getString(R.string.app_name)+".apk");
						     				mapaa.put(Fields.FILE_URL, updateFile.getFurl());
						     				mapaa.put(Fields.STORE_URL, "/updateCache/");
						     				mapaa.put(Fields.SERVER_INFO, serverinfo);

						     				Intent intent = new Intent();
						     				Bundle bundle = new Bundle();
						     				bundle.putSerializable("values", mapaa);
						     				intent.putExtras(bundle);
						     				intent.putExtra("runningThreadNum", 1);
						     				intent.setAction(DownloadService.DOWNLOAD_ACTION);
						     				intent.setClass(UserManage.this, DownloadService.class);
						     				UserManage.this.startService(intent);
						     				Toast.makeText(UserManage.this,
						    						"已启动后台服务下载更新文件！",
						    						Toast.LENGTH_SHORT).show();
						     				Log.v("UserManage", "Download Start!");
									}
								}).show();
					}else{
						new AlertDialog.Builder(UserManage.this)
						.setTitle("警告")
						.setMessage("有新版本，是否下载？")
						.setNegativeButton("取消",
								new DialogInterface.OnClickListener() {

									public void onClick(DialogInterface dialog,
											int which) {
									}
								})
						.setPositiveButton("下载",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int whichButton) {
										
										java.io.File cache = UserManage.this.getCacheDir();
					             		java.io.File cacheServerinfoFile = new java.io.File(cache,
					             				Fields.SERVER_INFO);
					                	 Server serverinfo = (Server) FileUtil
					             				.ReadObjectFromFile(cacheServerinfoFile.getAbsolutePath());
										 HashMap<String, Object> mapaa = new HashMap<String, Object>();
						     				mapaa.put(Fields.FILE_NAME, UserManage.this.getResources().getString(R.string.app_name)+".apk");
						     				mapaa.put(Fields.FILE_URL, updateFile.getFurl());
						     				mapaa.put(Fields.STORE_URL, "/updateCache/");
						     				mapaa.put(Fields.SERVER_INFO, serverinfo);

						     				Intent intent = new Intent();
						     				Bundle bundle = new Bundle();
						     				bundle.putSerializable("values", mapaa);
						     				intent.putExtras(bundle);
						     				intent.putExtra("runningThreadNum", 1);
						     				intent.setAction(DownloadService.DOWNLOAD_ACTION);
						     				intent.setClass(UserManage.this, DownloadService.class);
						     				UserManage.this.startService(intent);
						     				Toast.makeText(UserManage.this,
						    						"已启动后台服务下载更新文件！",
						    						Toast.LENGTH_SHORT).show();
						     				Log.v("UserManage", "Download Start!");
									}
								}).show();
					}
					
					
				}else{
					new AlertDialog.Builder(UserManage.this)
					.setTitle("警告")
					.setMessage("您使用的已是最新版本")
					.setPositiveButton("确定",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
								}
							}).show();
					//Toast.makeText(UserManage.this,"没有更新信息！",Toast.LENGTH_SHORT).show();
				}
				break;
			default:
				break;
			}
			super.handleMessage(msg);
		}
	
};
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		// 按下键盘上返回按钮
		if (keyCode == KeyEvent.KEYCODE_BACK) {

			new AlertDialog.Builder(UserManage.this)
					.setTitle("警告")
					.setMessage("您确定要退出吗？")
					.setNegativeButton("取消",
							new DialogInterface.OnClickListener() {

								public void onClick(DialogInterface dialog,
										int which) {
								}
							})
					.setPositiveButton("确定",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
									//finish();
									Intent startMain = new Intent(Intent.ACTION_MAIN); 
					                 startMain.addCategory(Intent.CATEGORY_HOME); 
					                 startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
					                 startActivity(startMain); 
					                 System.exit(0);
								}
							}).show();

			return true;
		} else {
			return super.onKeyDown(keyCode, event);
		}
	}

	private boolean accessToInternet() {
		ConnectivityManager cManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo info = cManager.getActiveNetworkInfo();
		if (info != null && info.isAvailable()) {
			return true;
		} else {
			return false;
		}
	}

}